/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciCxResult.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.modelDemand.domain.ModelDemandAuditLog;
import com.fzhucc.modules.modelDemand.repository.ModelDemandAuditLogRepository;
import com.fzhucc.modules.sciCxResult.domain.SciCxResult;
import com.fzhucc.modules.sciCxResult.domain.SciCxResultInfo;
import com.fzhucc.modules.sciCxResult.domain.dto.*;
import com.fzhucc.modules.sciCxResult.repository.SciCxResultInfoRepository;
import com.fzhucc.modules.sciCxResult.service.mapstruct.SciCxResultInfoMapper;
import com.fzhucc.modules.sciStudio.domain.SciStudio;
import com.fzhucc.modules.sciStudio.domain.SciStudioImg;
import com.fzhucc.modules.sciStudio.domain.SciStudioInfo;
import com.fzhucc.modules.sciStudio.domain.dto.*;
import com.fzhucc.modules.sciStudio.repository.SciStudioRepository;
import com.fzhucc.modules.sciStudio.service.mapstruct.SciStudioMapper;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.SciTechnologyDemandDto;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.utils.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciCxResult.repository.SciCxResultRepository;
import com.fzhucc.modules.sciCxResult.service.mapstruct.SciCxResultMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-01-10
 **/
@Service
@RequiredArgsConstructor
public class SciCxResultService {

    private final SciCxResultRepository sciCxResultRepository;

    private final SciStudioRepository sciStudioRepository;

    private final SciStudioMapper sciStudioMapper;

    private final ModelDemandAuditLogRepository modelDemandAuditLogRepository;
    private final SciCxResultMapper sciCxResultMapper;

    private final SciCxResultInfoMapper sciCxResultInfoMapper;

    private final UserRepository userRepository;

    private final SciCxResultInfoRepository sciCxResultInfoRepository;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${sci.audit.qxdsh}")
    public String qxdsh;

    @Value("${sci.audit.sjdsh}")
    public String sjdsh;

    @Value("${sci.audit.shtg}")
    public String shtg;

    @Value("${sci.audit.bh}")
    public String bh;

    @Value("${sci.doStatus}")
    public String ppz;

    @Value("${sci.doStatusypp}")
    public String ypp;

    @Value("${sci.doStatusyjj}")
    public String yjj;

    @Value("${sci.log.cxcg}")
    public String cxcg;

    @Value("${sci.stage.quPass}")
    public String quPass;

    @Value("${sci.stage.quNoPass}")
    public String quNoPass;

    @Value("${sci.stage.cityPass}")
    public String cityPass;

    @Value("${sci.stage.cityNoPass}")
    public String cityNoPass;

    @Transactional(rollbackFor = Exception.class)
    public void auditSciCxcg(AuditSciCxcgDto dto) {
        Optional<SciCxResult> res = sciCxResultRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到创新成果id");
        }
        String cAuditStatus = dto.getAuditStatus();
        if (cAuditStatus == null || cAuditStatus.equals("")) {
            throw new BadRequestException("缺少审核状态");
        }
        SciCxResult sciCxResult = res.get();
        //TODO 根据登录用户如果是市 的则审核市的字段    如果是区的则审核区的字段  admin暂不处理
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<User> resUser = userRepository.findById(userId);
        if (!resUser.isPresent()) {
            throw new BadRequestException("未找到登录用户");
        }
        User user = resUser.get();
        String orgArea = user.getOrgArea();
        //TODO 如果orgArea里面有2个 ; 表示市级审核   3个; 表示区级审核  其他则不与通过
        if (orgArea == null || orgArea.equals("")) {
            throw new BadRequestException("缺少地区区域无法审核");
        }
        if (!orgArea.contains(";")) {
            throw new BadRequestException("地区区域不符合规范无法审核");
        }
        String[] results = orgArea.split(";");
        if (results.length == 1) {
            throw new BadRequestException("省级账号无法审核");
        } else if (results.length == 2) {
            if (cAuditStatus.equals(bh)) {//驳回
                if (!sciCxResult.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //市级审核驳回 就变成区级待审核
                sciCxResult.setAuditStatus(qxdsh);
                sciCxResult.setIsEdit(1);//驳回设置为可编辑
                SciCxResult save = sciCxResultRepository.save(sciCxResult);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核驳回建议
                modelDemandAuditLog.setType(cxcg);
                modelDemandAuditLog.setStage(cityNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                if (!sciCxResult.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //区级审核通过 市级审核通过则通过
                sciCxResult.setAuditStatus(shtg);
                if (sciCxResult.getIsEdit() == 1) {

                } else {
                    sciCxResult.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                //审核通过设为显示
                sciCxResult.setIsShow(1);
                SciCxResult save = sciCxResultRepository.save(sciCxResult);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(cxcg);
                modelDemandAuditLog.setStage(cityPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else if (results.length == 3) {
            if (cAuditStatus.equals(bh)) {//驳回
                //区级审核
                sciCxResult.setIsEdit(1);//驳回设置为可编辑
                sciCxResult.setAuditStatus(cAuditStatus);
                SciCxResult save = sciCxResultRepository.save(sciCxResult);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(cxcg);
                modelDemandAuditLog.setStage(quNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                //区级审核通过 变为市级待审核
                sciCxResult.setAuditStatus(sjdsh);
                if (sciCxResult.getIsEdit() == 1) {

                } else {
                    sciCxResult.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                SciCxResult save = sciCxResultRepository.save(sciCxResult);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(cxcg);
                modelDemandAuditLog.setStage(quPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else {
            throw new BadRequestException("未符合的审级权限无法审核");
        }
    }

    //根据不同设置不同的部门查看
    public String setCriteria(SciCxResultQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2) )) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2) )) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void isAllowEdit(AllowSciCxResultDto dto) {
        Optional<SciCxResult> res = sciCxResultRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到创新成果");
        }
        Integer isEdit = dto.getIsEdit();
        if (isEdit == null) {
            throw new BadRequestException("缺少参数");
        }
        if (isEdit != 0 && isEdit != 1) {
            throw new BadRequestException("参数错误无法操作");
        }
        SciCxResult sciCxResult = res.get();
        sciCxResult.setIsEdit(isEdit);
        sciCxResultRepository.save(sciCxResult);
    }

    public Map<String, Object> my(SciCxResultQueryCriteria criteria, Pageable pageable) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        Page<SciCxResult> page = sciCxResultRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciCxResultDto> map = page.map(sciCxResultMapper::toDto);
        List<SciCxResultDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciCxResultDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), cxcg);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciCxResultInfo> lists = sciCxResultInfoRepository.findByCxId(dto.getId());
                dto.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists));

                Optional<SciStudio> ops = sciStudioRepository.findById(dto.getStudioId());
                if (ops.isPresent()){
                    dto.setStudioDto(sciStudioMapper.toDto(ops.get()));
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAll(SciCxResultQueryCriteria criteria, Pageable pageable) {
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            }else{
                criteria.setOrgArea(str);
            }
        }else{
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas()!=null && criteria.getOrgAreas().length==3){
                if (str.contains(criteria.getOrgAreas()[1])){
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            }else{
                criteria.setOrgArea(str);
            }
        }
        criteria.setIsDelete(0);
        criteria.setOrgAreas(null);
        Page<SciCxResult> page = sciCxResultRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciCxResultDto> map = page.map(sciCxResultMapper::toDto);
        List<SciCxResultDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciCxResultDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), cxcg);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciCxResultInfo> lists = sciCxResultInfoRepository.findByCxId(dto.getId());
                dto.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists));

                Optional<SciStudio> ops = sciStudioRepository.findById(dto.getStudioId());
                if (ops.isPresent()){
                    dto.setStudioDto(sciStudioMapper.toDto(ops.get()));
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAllh5(SciCxResultQueryCriteria criteria, Pageable pageable) {
        criteria.setIsDelete(0);
        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals(all)) {
            //h5的直接传orgArea
            criteria.setOrgArea(null);
        }
        Page<SciCxResult> page = sciCxResultRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciCxResultDto> map = page.map(sciCxResultMapper::toDto);
        List<SciCxResultDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciCxResultDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), cxcg);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciCxResultInfo> lists = sciCxResultInfoRepository.findByCxId(dto.getId());
                dto.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists));

                Optional<SciStudio> ops = sciStudioRepository.findById(dto.getStudioId());
                if (ops.isPresent()){
                    dto.setStudioDto(sciStudioMapper.toDto(ops.get()));
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<SciCxResultDto> queryAll(SciCxResultQueryCriteria criteria) {
        //导出  如果有传则按传的数组 导出
        criteria.setIsDelete(0);
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            }else{
                criteria.setOrgArea(str);
            }
        }else{
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas()!=null && criteria.getOrgAreas().length==3){
                if (str.contains(criteria.getOrgAreas()[1])){
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            }else{
                criteria.setOrgArea(str);
            }
        }
        return sciCxResultMapper.toDto(sciCxResultRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }
    public List<SciCxResultDto> queryAllmy(SciCxResultQueryCriteria criteria) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        return sciCxResultMapper.toDto(sciCxResultRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }


    @Transactional
    public SciCxResultDto findById(Integer id) {
        SciCxResult sciCxResult = sciCxResultRepository.findById(id).orElseGet(SciCxResult::new);
        ValidationUtil.isNull(sciCxResult.getId(), "SciCxResult", "id", id);
        //查询热度 +1
        Integer hot = sciCxResult.getHot();
        sciCxResult.setHot(hot + 1);
        SciCxResult save = sciCxResultRepository.save(sciCxResult);
        SciCxResultDto dto = sciCxResultMapper.toDto(save);

        String orgArea = dto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            dto.setOrgAreas(array);
        } else {
            String[] array = {};
            dto.setOrgAreas(array);
        }

        List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), cxcg);
        dto.setListModelDemandAuditLog(modelDemandAuditLogs);

        List<SciCxResultInfo> lists = sciCxResultInfoRepository.findByCxId(dto.getId());
        dto.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists));

        Optional<SciStudio> ops = sciStudioRepository.findById(dto.getStudioId());
        if (ops.isPresent()){
            dto.setStudioDto(sciStudioMapper.toDto(ops.get()));
        }
        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    public SciCxResultDto create(SciCxResultAddDto dto) {
        Integer studioId = dto.getStudioId();
        Optional<SciStudio> ops = sciStudioRepository.findById(studioId);
        if (!ops.isPresent()){
            throw new BadRequestException("请选择工作室");
        }

        String name = dto.getName();
        if (name == null) {
            throw new BadRequestException("成果名称为空");
        }

        SciCxResult resources = new SciCxResult();

        resources.setPic(dto.getPic());
        resources.setName(name);
        resources.setSbUnit(dto.getSbUnit());
        resources.setStudioId(studioId);
        resources.setStudioName(dto.getStudioName());
        resources.setStudioYear(dto.getStudioYear());
        resources.setIsEdit(0);//设置默认添加不可编辑
        resources.setHot(0);
        resources.setType(dto.getType());
        resources.setStudioLeaderName(dto.getStudioLeaderName());
        resources.setStudioLeaderHonor(dto.getStudioLeaderHonor());
        resources.setSbName(dto.getSbName());
        resources.setSbWays(dto.getSbWays());
        resources.setZlType(dto.getZlType());
        resources.setZlStatus(dto.getZlStatus());
        resources.setZlTime(dto.getZlTime());
        resources.setSsWays(dto.getSsWays());
        resources.setProfit(dto.getProfit());
        resources.setProInput(dto.getProInput());
        resources.setDetails(dto.getDetails());
        resources.setAnnualOutput(dto.getAnnualOutput());
        resources.setFirstName(dto.getFirstName());
        resources.setFirstSex(dto.getFirstSex());
        resources.setFirstPost(dto.getFirstPost());
        resources.setFirstTitle(dto.getFirstTitle());
        resources.setFirstUnit(dto.getFirstUnit());
        resources.setFirstWay(dto.getFirstWay());
        resources.setIsDelete(0);
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setIsShow(0);
        resources.setSort(1);
        resources.setAuditStatus(qxdsh);//区县待审核
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        SciCxResultDto sciCxResultDto = sciCxResultMapper.toDto(sciCxResultRepository.save(resources));

        //根据id设置sort
        Optional<SciCxResult> result = sciCxResultRepository.findById(sciCxResultDto.getId());
        if (result.isPresent()){
            SciCxResult sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            sciCxResultRepository.save(sciCxResult);
        }


        List<SciCxResultInfoAddDto> listSciCxResultInfo = dto.getListSciCxResultInfo();
        if (listSciCxResultInfo != null && listSciCxResultInfo.size() > 0) {
            for (SciCxResultInfoAddDto res : listSciCxResultInfo) {
                SciCxResultInfo sciCxResultInfo = new SciCxResultInfo();
                sciCxResultInfo.setName(res.getName());
                sciCxResultInfo.setUnit(res.getUnit());
                sciCxResultInfo.setTitle(res.getTitle());
                sciCxResultInfo.setSex(res.getSex());
                sciCxResultInfo.setPost(res.getPost());
                sciCxResultInfo.setCxId(sciCxResultDto.getId());
                sciCxResultInfoRepository.save(sciCxResultInfo);
            }
        }

        List<SciCxResultInfo> list1 = sciCxResultInfoRepository.findByCxId(sciCxResultDto.getId());
        sciCxResultDto.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(list1));

        String orgArea = sciCxResultDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            sciCxResultDto.setOrgAreas(array);
        } else {
            String[] array = {};
            sciCxResultDto.setOrgAreas(array);
        }

        return sciCxResultDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(SciCxResultEditDto dto) {
        SciCxResult sciCxResult = sciCxResultRepository.findById(dto.getId()).orElseGet(SciCxResult::new);
        //TODO 如果编辑时为驳回状态则 调整为区县待审核
        if (sciCxResult.getAuditStatus().equals(bh)){
            sciCxResult.setAuditStatus(qxdsh);
        }
        ValidationUtil.isNull(sciCxResult.getId(), "SciCxResult", "id", dto.getId());

        Integer studioId = dto.getStudioId();
        Optional<SciStudio> ops = sciStudioRepository.findById(studioId);
        if (!ops.isPresent()){
            throw new BadRequestException("请选择工作室");
        }
        String name = dto.getName();
        if (name == null) {
            throw new BadRequestException("成果名称为空");
        }
        sciCxResult.setPic(dto.getPic());
        sciCxResult.setName(name);
        sciCxResult.setSbUnit(dto.getSbUnit());
        sciCxResult.setStudioId(studioId);
        sciCxResult.setStudioName(dto.getStudioName());
        sciCxResult.setStudioYear(dto.getStudioYear());
        sciCxResult.setType(dto.getType());
        sciCxResult.setStudioLeaderName(dto.getStudioLeaderName());
        sciCxResult.setStudioLeaderHonor(dto.getStudioLeaderHonor());
        sciCxResult.setSbName(dto.getSbName());
        sciCxResult.setSbWays(dto.getSbWays());
        sciCxResult.setZlType(dto.getZlType());
        sciCxResult.setZlStatus(dto.getZlStatus());
        sciCxResult.setZlTime(dto.getZlTime());
        sciCxResult.setSsWays(dto.getSsWays());
        sciCxResult.setProfit(dto.getProfit());
        sciCxResult.setProInput(dto.getProInput());
        sciCxResult.setDetails(dto.getDetails());
        sciCxResult.setAnnualOutput(dto.getAnnualOutput());
        sciCxResult.setFirstName(dto.getFirstName());
        sciCxResult.setFirstSex(dto.getFirstSex());
        sciCxResult.setFirstPost(dto.getFirstPost());
        sciCxResult.setFirstTitle(dto.getFirstTitle());
        sciCxResult.setFirstUnit(dto.getFirstUnit());
        sciCxResult.setFirstWay(dto.getFirstWay());
        sciCxResult.setIsShow(dto.getIsShow());
        sciCxResult.setSort(dto.getSort());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            sciCxResult.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            sciCxResult.setOrgArea(orgAreaReturn());
        }
        SciCxResult save = sciCxResultRepository.save(sciCxResult);


        List<SciCxResultInfoAddDto> listSciCxResultInfo = dto.getListSciCxResultInfo();
        if (listSciCxResultInfo != null && listSciCxResultInfo.size() > 0) {
            List<SciCxResultInfo> all3 = sciCxResultInfoRepository.findByCxId(save.getId());
            if (all3 != null && all3.size() > 0) {
                for (SciCxResultInfo result : all3) {
                    sciCxResultInfoRepository.deleteById(result.getId());
                }
            }
            for (SciCxResultInfoAddDto res : listSciCxResultInfo) {
                SciCxResultInfo sciCxResultInfo = new SciCxResultInfo();
                sciCxResultInfo.setName(res.getName());
                sciCxResultInfo.setUnit(res.getUnit());
                sciCxResultInfo.setTitle(res.getTitle());
                sciCxResultInfo.setSex(res.getSex());
                sciCxResultInfo.setPost(res.getPost());
                sciCxResultInfo.setCxId(save.getId());
                sciCxResultInfoRepository.save(sciCxResultInfo);
            }
        }

    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //sciCxResultRepository.deleteById(id);
            //假删除
            Optional<SciCxResult> res = sciCxResultRepository.findById(id);
            if (res.isPresent()) {
                SciCxResult sciCxResult = res.get();
                sciCxResult.setIsDelete(1);
                sciCxResultRepository.save(sciCxResult);
            }
        }
    }

    public List<DictDetailDto> getCxResultType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("cx_result_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    public List<DictDetailDto> getCxResultZlType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("cx_result_zl_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getCxResultZlStatus() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("cx_result_zl_status");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public void download(List<SciCxResultDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciCxResultDto sciCxResult : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("工作室id", sciCxResult.getStudioId());
            map.put("申报单位", sciCxResult.getSbUnit());
            map.put("成果名称", sciCxResult.getName());
            map.put("成果类别", sciCxResult.getType());
            map.put("所属工作室名称", sciCxResult.getStudioName());
            map.put("获得市级工作室年份", sciCxResult.getStudioYear());
            map.put("工作室领衔人名称", sciCxResult.getStudioLeaderName());
            map.put("领衔人最高荣誉", sciCxResult.getStudioLeaderHonor());
            map.put("申报联系人姓名", sciCxResult.getSbName());
            map.put("申报联系人联系方式", sciCxResult.getSbWays());
            map.put("专利形式", sciCxResult.getZlType());
            map.put("专利状况", sciCxResult.getZlStatus());
            map.put("专利批准时间", sciCxResult.getZlTime());
            map.put("成果实施方式", sciCxResult.getSsWays());
            map.put("项目投入资金情况", sciCxResult.getProInput());
            map.put("年产值", sciCxResult.getAnnualOutput());
            map.put("利润", sciCxResult.getProfit());
            map.put("第一完成人姓名", sciCxResult.getFirstName());
            map.put("第一完成人性别", sciCxResult.getFirstSex());
            map.put("第一完成人职务", sciCxResult.getFirstPost());
            map.put("第一完成人职称", sciCxResult.getFirstTitle());
            map.put("第一完成人工作单位", sciCxResult.getFirstUnit());
            map.put("第一完成人联系电话", sciCxResult.getFirstWay());
            map.put("简介", sciCxResult.getDetails());
            map.put("成果图图片", sciCxResult.getPic());
            map.put("是否删除 默认否", sciCxResult.getIsDelete());
            map.put("区审核状态 默认未审核  zqx_audit_status", sciCxResult.getAuditStatus());
            map.put("是否小程序展示", sciCxResult.getIsShow());
            map.put("排序", sciCxResult.getSort());
            map.put("填报用户", sciCxResult.getUserId());
            map.put("热度", sciCxResult.getHot());
            map.put("是否允许编辑默认否", sciCxResult.getIsEdit());
            String orgArea = sciCxResult.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}